package com.isoftstone.common.service.impl;


import com.isoftstone.common.Page;
import com.isoftstone.common.Tidings;
import com.isoftstone.common.dao.SysUserMapper;
import com.isoftstone.common.entity.SysUser;
import com.isoftstone.common.service.ISysUserService;
import com.isoftstone.merchant.dao.city.CityMapper;
import com.isoftstone.merchant.dao.merchant.MerchantMapper;
import com.isoftstone.merchant.entity.city.City;
import com.isoftstone.merchant.entity.merchant.Merchant;
import com.isoftstone.util.Const;
import com.isoftstone.util.MD5;
import com.isoftstone.util.PageData;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service
public class SysUserService implements ISysUserService {

	@Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    MerchantMapper merchantMapper;
    @Autowired
    CityMapper cityMapper;

    public SysUser getUserByUserName(String userName) throws Exception {
        return sysUserMapper.getUserByUserName(userName);
    }

    public SysUser getUserDeptById(String userId) throws Exception {
        return sysUserMapper.getUserDeptById(userId);
    }
        @Transactional
    public List<SysUser> getUserlistPage(Page page) throws Exception {
        return sysUserMapper.getUserlistPage(page);
    }

    @Override
    public List<SysUser> getBankUserlistPage(Page page) throws Exception {
        return sysUserMapper.getBankUserlistPage(page);
    }

    @Transactional
    public void saveUserIP(SysUser user) throws Exception {
        sysUserMapper.saveUserIP(user);
    }

    @Transactional
    public void saveUser(SysUser user) throws Exception {
        sysUserMapper.saveUser(user);
    }

    @Transactional
    public void updateUser(SysUser user) throws Exception {
        sysUserMapper.updateUser(user);
    }

    @Transactional
    public void deleteAllU(String[] userIds) throws Exception {
        sysUserMapper.deleteAllU(userIds);
    }

    @Transactional
    @Override
    public void updateRetryCount(String userName,Integer retryCount) {
        sysUserMapper.updateRetryCount(userName,retryCount);
    }

    @Override
    public String getuserIdByuserId(String userid) throws Exception {
        return sysUserMapper.getuserIdByuserId(userid);
    }

    @Override
    /*
    * 根据商户编号 、system、员工编号查询
    * */
    public SysUser getSysUserByCorpIdAndUserId(String corpId,String userId) throws Exception {
        return sysUserMapper.getSysUserByCorpIdAndUserId(corpId,userId);
    }

    @Override
    public String getnumber() throws Exception {
        return sysUserMapper.getnumber();
    }

    @Override
    public SysUser getUserById(String userid) throws Exception {
        return sysUserMapper.getUserById(userid);
    }

    @Override
    public SysUser getUserByRoleId(String roleId) throws Exception {
        return sysUserMapper.getUserByRoleId(roleId);
    }

    @Override
    @Transactional
    public void deleteSysUserbyUserId(String userid) throws Exception {
        sysUserMapper.deleteSysUserbyUserId(userid);
    }

    @Override
    public Tidings<String> saveMercantManager(SysUser sysUser, HttpServletRequest request, SysUser user) throws Exception {
        Tidings<String>  tidings = new Tidings<String>();

        sysUser.setUsercode(getUsercode(sysUser));//商户编号
        sysUser.setType("01");//01--超级管理员 02--管理员 03--柜员
//        sysUser.setCorpId(this.getUser().getCorpId());//商户编号
        String string= DigestUtils.md5Hex("a747cea3c1efabd3b5f5b60a81be59b6" + "-" + sysUser.getUsercode()).toUpperCase();
        sysUser.setPassword(string);//密码
        sysUser.setStatus("02");//01：未审核02：正常 03：禁用
        sysUser.setCreateDate(new Date());//创建时间
        sysUser.setCreator(user.getUserid());//创建人
        sysUser.setSystem("02");
        sysUser.setLastUpdateDate(new Date());
//        sysUser.setRoleid("2");//管理员

        this.sysUserMapper.saveUser(sysUser);

        tidings.setStatus(Const.SUCCESS);
        tidings.setMsg("保存管理员信息成功");
        return   tidings;
    }

    @Override
    public void deleteSysUserbyUserIdandCorpId(String userid, String corpId) throws Exception {
        sysUserMapper.deleteSysUserbyUserIdandCorpId(userid,corpId);
    }

    @Override
    public SysUser getBankUserByUsercode(String usercode) {
        return sysUserMapper.getBankUserByUsercode(usercode);
    }

    @Override
    public int updateUserStatus(String usercode, String status) {
        return sysUserMapper.updateUserStatus(usercode,status);
    }

    /**
     * 通過商戶ID获取商户用户
     * @param pd
     * @return
     */
    @Override
    public String[] getMerchantUserListByCorpIds(PageData pd) {

        if(null != pd.get("corpId")){
            pd.put("corpId", Arrays.asList(pd.get("corpId").toString().split(",")));

            return this.sysUserMapper.getMerchantUserListByCorpIds(pd);
        }
        return new String[0];
    }

    @Override
    public String[] getFeeUserListByCorpIds(PageData pd) {

        if(null != pd.get("corpId")){
            pd.put("corpId", Arrays.asList(pd.get("corpId").toString().split(",")));

            return this.sysUserMapper.getFeeUserListByCorpIds(pd);
        }
        return new String[0];
    }

    @Override
    public String getUserCodeByUserCode(String userCode) throws Exception {
        return sysUserMapper.getUserCodeByUserCode(userCode);
    }

    @Override
    public String getStatusBycomUserCode(String comUserName) throws Exception {
        return sysUserMapper.getStatusBycomUserCode(comUserName);
    }

    @Override
    public List<SysUser> getallUser() throws Exception {
        return sysUserMapper.getallUser();
    }


    //显示登录用户信息
	public SysUser getShowUser(String userName) throws Exception {
		return sysUserMapper.getShowUser(userName);
	}

    @Override
    public Integer getUserRetryCount(String userName) throws Exception {
        return sysUserMapper.getUserRetryCount(userName);
    }
    //规则：地区代码(2 位)+项目编号(3 位)+序号(1 位)山东省分行中银快缴业务操作手册
    //    地区代码： 拼音首字母，如莱芜 lw；济南 jn；济宁 jg；聊城 lc；淄博 zb； …
    //    项目编号： 001 代表第一个单位项目， 002 代表第二个单位项目， …
    //    序 号： 1 表示第一个管理员，原则上只需要开立一个
    //    如莱芜的第一个单位项目的管理员编号： lw0011
    //    地区代码：选中商户的cityCode属性决定管理员的地区代码
    private String getUsercode(SysUser sysUser){
        Merchant merchant  = this.merchantMapper.selectByPrimaryKey(sysUser.getCorpId());



        City city = this.cityMapper.selectByPrimaryKey(merchant.getCityId());

        Page page = new Page();
        page.setShowCount(9999999);
        PageData pd = new PageData();
        pd.put("cityId",merchant.getCityId());
        page.setPd(pd);

//        int countMerchant =  this.merchantMapper.getMerchantlistPage(page).size();

        String projectNo = merchant.getCorpCode().substring(merchant.getCorpCode().length()-3,merchant.getCorpCode().length());
        int countManager = this.sysUserMapper.countUserByCorpId(city.getShorthand()+projectNo);

        return  city.getShorthand()+projectNo+(countManager+1);
    }



}
